import 'package:flutter/material.dart';
import 'package:gzmall_app/brands/brands_details_page.dart';
import 'package:gzmall_app/common/color_common.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:gzmall_app/common/refresh_listview.dart';
import 'package:gzmall_app/model/store.dart';
import 'package:gzmall_app/model/brand.dart';
import 'package:gzmall_app/common/net_util.dart';
import 'package:gzmall_app/common/api.dart';
import 'package:gzmall_app/model/favorites.dart';
import 'package:gzmall_app/store/store_detail_page.dart';

class FollowPage extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => FollowPageState();
}

class FollowPageState extends State<FollowPage> with TickerProviderStateMixin {
  List<Favorites> _stores = [];
  List<Favorites> _brands = [];

  TabController _tabController;

  RefreshListView _rListView1, _rListView2;
  int _curPage = 1;
  bool _showEmpty1 = false, _showEmpty2 = false;

  @override
  void initState() {
    super.initState();
    _tabController = TabController(length: 2, vsync: this);
    _tabController.addListener(() {
      switch (_tabController.index) {
        case 0:
          _getFavorites("Brand", 1);
          break;
        case 1:
          _getFavorites("Shop", 1);
          break;
        default:
      }
    });
    _getFavorites("Brand", 1);
  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: _createAppBar(),
      body: Container(
        color: Colors.white,
        child: new Column(children: <Widget>[
          new Container(
            height: 48.0,
            margin: const EdgeInsets.only(left: 50.0, right: 50.0),
            child: new TabBar(
              controller: _tabController,
              labelColor: ColorCommon.primaryColor,
              unselectedLabelColor: ColorCommon.grey6,
              tabs: <Widget>[
                new Tab(text: "品牌"),
                new Tab(text: "店铺"),
              ],
            ),
          ),
          new Expanded(
            child: new TabBarView(
              controller: _tabController,
              children: <Widget>[
                _createBrandList(),
                _createStoreList(),
              ],
            ),
          ),
        ]),
      ),
    );
  }

  _createAppBar() {
    return new AppBar(
      elevation: 0.0,
      title: new Text("我的关注"),
      leading: new IconButton(
        icon: new Icon(Icons.arrow_back_ios),
        onPressed: () {
          Navigator.of(context).pop();
        },
      ),
      actions: <Widget>[],
    );
  }

  _createStoreList() {
    _rListView2 = RefreshListView(
      enablePullDown: true,
      enablePullUp: true,
      onRefresh: _onRefresh,
      showEmpty: _showEmpty2,
      emptyView: _createEmptyWidget(),
      onReload: () {
        _getFavorites("Shop", 1);
      },
      child: ListView.builder(
        padding: const EdgeInsets.only(top: 0.0),
        itemCount: _stores.length,
        itemBuilder: (context, index) {
          Store store = _stores[index]?.shop;
          return InkWell(
            onTap: () {
              if (store != null) {
                Navigator.of(context).push(new MaterialPageRoute(builder: (_) {
                  return new StoreDetailPage(store: store);
                }));
              }
            },
            child: Container(
              margin: const EdgeInsets.only(bottom: 1.0),
              padding: const EdgeInsets.all(10.0),
              color: Colors.white,
              child: Row(children: <Widget>[
                store?.avatar != null
                    ? CachedNetworkImage(
                        imageUrl: store?.avatar,
                        height: 60.0,
                        width: 60.0,
                        fit: BoxFit.fill,
                      )
                    : Container(
                        color: Colors.grey,
                        height: 60.0,
                        width: 60.0,
                      ),
                Expanded(
                  child: Padding(
                    padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                    child: Text(
                      store?.name ?? "",
                      style:
                          TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                    ),
                  ),
                ),
                Padding(
                  padding: const EdgeInsets.only(right: 1.0),
                  child: Text(
                    "进店",
                    style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                  ),
                ),
                new Image.asset(
                  "images/right_arrow.png",
                  width: 10.0,
                  height: 10.0,
                ),
              ]),
            ),
          );
        },
      ),
    );
    return Container(
        color: ColorCommon.grey5,
        padding: const EdgeInsets.only(top: 1.0),
        child: _rListView2);
  }

  _createBrandList() {
    _rListView1 = RefreshListView(
      enablePullDown: true,
      enablePullUp: true,
      onRefresh: _onRefresh,
      showEmpty: _showEmpty1,
      emptyView: _createEmptyWidget(),
      onReload: () {
        _getFavorites("Brand", 1);
      },
      child: ListView.builder(
        padding: const EdgeInsets.only(top: 0.0),
        itemCount: _brands.length,
        itemBuilder: (context, index) {
          Brand brand = _brands[index].brand;
          return InkWell(
              onTap: () {
                if (brand?.id != null) {
                  Navigator.of(context)
                      .push(new MaterialPageRoute(builder: (_) {
                    return new BrandsDetailsPage(id: brand?.id);
                  }));
                }
              },
              child: Container(
                margin: const EdgeInsets.only(bottom: 1.0),
                padding: const EdgeInsets.all(10.0),
                color: Colors.white,
                child: Row(children: <Widget>[
                  brand?.avatar != null
                      ? CachedNetworkImage(
                          imageUrl: brand?.avatar,
                          height: 60.0,
                          width: 60.0,
                          fit: BoxFit.fill,
                        )
                      : Container(
                          color: Colors.grey,
                          height: 60.0,
                          width: 60.0,
                        ),
                  Expanded(
                    child: Padding(
                      padding: const EdgeInsets.only(left: 10.0, right: 10.0),
                      child: Text(
                        brand?.name ?? "",
                        style: TextStyle(
                            fontSize: 18.0, color: ColorCommon.black1),
                      ),
                    ),
                  ),
                  Padding(
                    padding: const EdgeInsets.only(right: 1.0),
                    child: Text(
                      "进入品牌",
                      style:
                          TextStyle(fontSize: 18.0, color: ColorCommon.black1),
                    ),
                  ),
                  new Image.asset(
                    "images/right_arrow.png",
                    width: 10.0,
                    height: 10.0,
                  ),
                ]),
              ));
        },
      ),
    );
    return Container(
        color: ColorCommon.grey5,
        padding: const EdgeInsets.only(top: 1.0),
        child: _rListView1);
  }

  Widget _createEmptyWidget() {
    return Container(
        width: double.infinity,
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Image.asset(
              "images/no_collection.png",
              width: 100.0,
              height: 100.0,
            ),
            Padding(
              padding: const EdgeInsets.only(top: 10.0),
              child: Text(
                '暂无关注记录',
                style: TextStyle(fontSize: 18.0, color: ColorCommon.black1),
              ),
            ),
          ],
        ));
  }

  RefreshListView _getRListView(String type) {
    if (type == "Shop") {
      return _rListView2;
    } else if (type == "Brand") {
      return _rListView1;
    }
  }

  void _onRefresh(bool up) {
    int p = up ? 1 : _curPage + 1;
    switch (_tabController.index) {
      case 0:
        _getFavorites("Brand", p);
        break;
      case 1:
        _getFavorites("Shop", p);
        break;
      default:
    }
  }

  _getFavorites(String type, int page) async {
    bool isGetNew = page == 1;
    Map<String, String> params = {"type": type, 'page': page.toString()};
    NetUtil.get(
        context,
        Api.favorites,
        (data, message) {
          if (!mounted) return;
          _curPage = page;
          var _dataList = (data as List)
              ?.map((e) => e == null ? null : Favorites.fromJson(e))
              ?.toList();
          setState(() {
            if (type == "Shop") {
              _showEmpty2 =
                  isGetNew && (_dataList == null || _dataList.length <= 0);
              if (isGetNew) {
                _stores = _dataList;
              } else {
                _stores.addAll(_dataList);
              }
            } else if (type == "Brand") {
              _showEmpty1 =
                  isGetNew && (_dataList == null || _dataList.length <= 0);
              if (isGetNew) {
                _brands = _dataList;
              } else {
                _brands.addAll(_dataList);
              }
            }
          });
          if (this._getRListView(type) != null) {
            this._getRListView(type).refreshCompleted(isGetNew,
                hasMore: _dataList != null && _dataList.length >= Api.pageSize);
          }
        },
        params: params,
        errorCallBack: (e) {
          setState(() {
            if (type == "Shop") {
              _showEmpty2 =
                  isGetNew && (_stores == null || _stores.length <= 0);
            } else if (type == "Brand") {
              _showEmpty1 =
                  isGetNew && (_brands == null || _brands.length <= 0);
            }
          });
          if (this._getRListView(type) != null) {
            this._getRListView(type).refreshCompleted(isGetNew);
          }
        });
  }
}
